<script setup lang="ts">
import { NForm } from "naive-ui";
import { TodoForm } from "../types";
import { priorityOptions } from "../components/constant";
import { useTodosStore } from "../store";

const todosStore = useTodosStore();
// 自动导入
const router = useRouter();


const formRef = ref<InstanceType<typeof NForm>>();


const formValues = reactive<TodoForm>({
  title: "",
  description: "",
  priority: "normal",
});
const todoId = ref(0)
onActivated(() => {
  const route = useRoute();//当前路由信息
  todoId.value = parseInt(route.params.id as string)
  const todo = todosStore.todos.find((i) => i.id == todoId.value)
   //判断todo是否有值，没有就是新增的值
  if (todo) {
    Object.assign(formValues, todo);
  }else
  Object.assign(formValues, {
    title: "",
    description: "",
    priority: "normal",
  });
});


const rules = {
  title: [
    { required: true, message: "请输入标题", trigger: "blur" },
    {
      min: 3,
      max: 50,
      message: "长度在 3 到 50 个字符",
      trigger: "blur",
    },
  ],
  description: [{ required: true, message: "请输入内容", trigger: "blur" }],
};
//
const newOrEditTodo = async () => {
  //  validate
  await formRef.value?.validate();
  // 发起请求并添加至 todos => todosStore 全局状态管理
  const success = todoId.value ? await todosStore.editTodo(formValues, todoId.value) : await todosStore.addTodo(formValues);
  if (success) router.push({ name: "todo.list" });
};
</script>
<template>
  <NForm ref="formRef" :model="formValues" :rules="rules">
    <h1>{{ todoId ? "新的" : "修改" }}代办</h1>
    <NFormItem path="title" label="Title">
      <NInput v-model:value="formValues.title" placeholder="please input your todo title" />
    </NFormItem>
    <NFormItem path="description" label="Description">
      <NInput type="textarea" :rows="10" v-model:value="formValues.description" />
    </NFormItem>
    <NFormItem label="Priority">
      <NSelect v-model:value="formValues.priority" :options="priorityOptions" />
    </NFormItem>
    <NButton class="w-full" size="large" type="primary" @click.prevent="newOrEditTodo">{{ todoId ? "新的" : "修改" }}代办
    </NButton>
  </NForm>
</template>
